package com.kaver.feign.rpc.eureka;

import org.springframework.cloud.openfeign.FeignClient;

import com.kaver.feign.rpc.support.SpringMvcFeign;

/**
 * @ClassName: EurekaServiceFactory
 * @Description: eureka服务工厂
 * @author kaver
 * @date 2019年5月29日 下午3:31:40
 * 
 */
public class EurekaServiceFactory {

	private static int DEFAULT_MAX_CONN = 20;

	private static int DEFAULT_TIMEOUT = 5000;

	private static int DEFAULT_RETRY_COUNT = 3;

	private static boolean DEFAULT_KEEPALIVE = false;

	private static String EUREKA_URL;

	public static void initConfig(String eurekaUrl, int maxConn, int timeout, int retry, boolean keepAlive) {
		EurekaServiceFactory.DEFAULT_MAX_CONN = maxConn;
		EurekaServiceFactory.DEFAULT_TIMEOUT = timeout;
		EurekaServiceFactory.DEFAULT_RETRY_COUNT = retry;
		EurekaServiceFactory.DEFAULT_KEEPALIVE = keepAlive;
		EurekaAppStatusScheduler.start();
	}

	public static void initConfig(String eurekaUrl) {
		EUREKA_URL = eurekaUrl;
		EurekaAppStatusScheduler.start();
	}

	public static String getEurekaUrl() {
		return EUREKA_URL;
	}

	public static <T> T get(Class<T> feignClient) {
		String url = getUrl(feignClient);
		return SpringMvcFeign.target(feignClient, url, DEFAULT_MAX_CONN, DEFAULT_TIMEOUT, DEFAULT_RETRY_COUNT,
				DEFAULT_KEEPALIVE);
	}
	public static <T> T get(Class<T> feignClient, String url) {
        return SpringMvcFeign.target(feignClient, url, DEFAULT_MAX_CONN, DEFAULT_TIMEOUT, DEFAULT_RETRY_COUNT,
            DEFAULT_KEEPALIVE);
    }

	public static <T> T get(Class<T> feignClient, int maxConn, int timeout, int retry, boolean keepAlive) {
		String url = getUrl(feignClient);
		return SpringMvcFeign.target(feignClient, url, maxConn, timeout, retry, keepAlive);
	}

	public static String getFeignClientAppName(Class<?> feignClient) {
		FeignClient client = feignClient.getAnnotation(FeignClient.class);
		if (client == null) {
			return null;
		}
		return client.value();
	}

	public static String getUrl(Class<?> feignClient) {
		String appName = getFeignClientAppName(feignClient);
		if (appName == null || "".equals(appName)) {
			throw new RuntimeException("feignClient do not have value");
		}
		EurekaAppInstance appInstance = EurekaAppCache.getRealRandomEurekaAppInstance(appName);
		if (appInstance == null) {
			throw new RuntimeException("feignClient do not have appInstance");
		}
		return appInstance.toHttpUri();
	}
}
